package com.qf.util;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;

public class AliSmsUtil {
    /**必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。*/
    private static final String SMS_KEY="LTAI5tEezxYStbwuZaGH2saP";
    /**必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。*/
    private static final String SMS_SECRET="4jTpGfEIRMuX1DS6VCMPx4Go04y3vd";
    /**登录验证码模板*/
    public static final String SMS_TEM_CODE="SMS_306880956";
    /**
     * 阿里云短信客户端对象 */
    private static Client client;
    static {
        Config config = new Config()
                .setAccessKeyId(SMS_KEY)
                .setAccessKeySecret(SMS_SECRET);
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            client= new Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送短信验证码
     * @param template 短信模板
     * @param phone 手机号
     * @param code 验证码
     * @return 是否发送成功*/
    public static boolean sendCode(String template,String phone,String code){
        //1.创建请求对象
        SendSmsRequest request = new SendSmsRequest()
                .setSignName("来自SelfCare官方的短信")
                .setTemplateCode(template)
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\""+code+"\"}");
        //2.执行请求 获取响应
        try {
            SendSmsResponse response = client.sendSmsWithOptions(request,new com.aliyun.teautil.models.RuntimeOptions());
            //3.验证当前请求是否成功
            return response.getBody().getCode().equals("OK");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
